package com.jiubanqingchen.framework.support;

import cn.hutool.core.date.DateUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.jfinal.kit.StrKit;
import com.jiubanqingchen.framework.exception.WishException;
import com.jiubanqingchen.framework.exception.WishExceptionKey;
import com.jiubanqingchen.kit.ApplicationKit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * jwt工具 创建校验token
 *
 * @author light_dust
 * @since 2020/9/24 10:16
 */
public class JwtSupport {

    private static final JwtSupport me = new JwtSupport();

    public static JwtSupport me() {
        return me;
    }

    private final Logger logger = LoggerFactory.getLogger(JwtSupport.class);
    /**
     * 签名密匙
     */
    private final String SECRET = "20C89E7E1FAFB705AD025AEA613FD5F7"; //SecureUtil.md5("jiubanqingchen@2019").toUpperCase();

    /**
     * 创建token信息
     *
     * @param userId 用户id
     * @author light_dust
     * @since 2020/9/24 10:29
     **/
    public String createToken(String userId) throws WishException {
        Map<String, Object> headerClaims = new HashMap<>();
        headerClaims.put("alg", "HS256");
        headerClaims.put("typ", "JWT");
        // 使用 HS256算法
        try {
            return JWT.create().withIssuer("light_dust").withHeader(headerClaims)
                    .withExpiresAt(DateUtil.offsetSecond(new Date(), ApplicationKit.me().getTokenEffective()))
                    .withClaim("userId", userId).sign(Algorithm.HMAC256(SECRET));
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new WishException(WishExceptionKey.USER_TOKEN_CREATE_FAIL, e.getCause());
        }
    }

    /**
     * 解析token 得到用户id
     *
     * @param token 用户token信息
     * @author light_dust
     * @since 2020/9/24 10:29
     **/
    public String verifyToken(String token) throws WishException {
        if (StrKit.isBlank(token)) return null;
        try {
            JWTVerifier jWTVerifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
            DecodedJWT jwtToken = jWTVerifier.verify(token);
            return jwtToken.getClaim("userId").asString();
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new WishException(WishExceptionKey.USER_TOKEN_TIME_OUT, e.getCause());
        }
    }

}
